<template>
  <div id="smartSreach">
    <div class="smartSreach_content">
      <div class="inputBigBox">
        <el-input v-model="filterData.searchValue" placeholder="请输入多个关键字搜索，多个关键字以，隔开"></el-input>
        <el-button @click="searchInfo" type="primary">搜索</el-button>
      </div>
      <template v-if="showResult">
        <h3 class="infoList_title">筛选区</h3>
        <ul class="infoList_filter">
          <li class="infoList_filter_item singular">
            <span>时间范围：</span>
            <el-radio v-model="filterData.filterTimeType" :label="1">今天</el-radio>
            <el-radio v-model="filterData.filterTimeType" :label="2">24小时</el-radio>
            <el-radio v-model="filterData.filterTimeType" :label="3">3天</el-radio>
            <el-radio v-model="filterData.filterTimeType" :label="4">7天</el-radio>
            <el-radio class="defineTimeBtn" v-model="filterData.filterTimeType" :label="5">
              <template slot-scope>
                自定义
                <i>></i>
              </template>
            </el-radio>
            <el-date-picker
              :class="dateRangeClass"
              v-model="defineDate"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </li>
          <li class="infoList_filter_item">
            <span>舆论情绪：</span>
            <el-radio v-model="filterData.filterEmotionType" :label="1">全部</el-radio>
            <el-radio v-model="filterData.filterEmotionType" :label="2">正面</el-radio>
            <el-radio v-model="filterData.filterEmotionType" :label="3">中立</el-radio>
            <el-radio v-model="filterData.filterEmotionType" :label="4">负面</el-radio>
          </li>
          <li class="infoList_filter_item filterCheckBox" style="width: 100%">
            <el-radio
              v-for="(item, index) in statList"
              v-model="filterData.filterFromType"
              :label="item.classify"
              :key="index"
            >
              <template>
                <span>{{item.name}}</span>
                <br />
                <span>{{item.value}}</span>
              </template>
            </el-radio>
          </li>
        </ul>
        <h3 class="infoList_title" style="margin:40px 0px 30px 0px">监测结果</h3>
        <div class="tableBox">
          <div class="tableBtnGroup">
            <el-button size="mini" icon @click="multiAddDir">加入素材</el-button>
            <el-button size="mini" icon @click="addCollection">收藏</el-button>
            <el-button size="mini" icon @click="setSortType(1)">时间排序</el-button>
            <el-button size="mini" icon @click="setSortType(2)">热度排序</el-button>
          </div>
          <el-input
            class="filterInput"
            placeholder="输入关键字在结果中搜索"
            prefix-icon="el-icon-search"
            v-model="filterData.resultWords"
          ></el-input>
          <el-button type="success" size="mini" class="visibilyBtn" @click="initSearchList(1)">搜索</el-button>
          <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="35"></el-table-column>
            <el-table-column label="全选本页">
              <template slot-scope="scope">
                <div class="newsBox">
                  <h3 class="newsTitle">{{scope.row.title}}</h3>
                  <div class="newsContent">{{scope.row.content}}</div>
                  <span class="newsTime">{{scope.row.publishTime}}</span>
                  <span class="newsResource">文章来源：{{scope.row.source}}</span>
                  <span class="newsTrigger">触发关键词：{{scope.row.keyword}}</span>
                </div>
                <div class="newsRelevant">
                  <span class="rele">相关舆情{{scope.row.simNum}}条</span>
                  <a :href="scope.row.url" target="_blank">查看原文</a>
                  <br />
                  <span class="newsBtn news_warn" @click="controller(scope.row, 1)">预警</span>
                  <span class="newsBtn news_copy" @click="controller(scope.row, 2)">复制文章</span>
                  <span
                    v-if="!scope.row.collectId"
                    class="newsBtn news_collect"
                    @click="controller(scope.row, 3)"
                  >收藏</span>
                  <span v-else class="newsBtn news_collected" @click="cancelCollect(scope.row)">收藏</span>
                  <!-- <span class="newsBtn news_read">已读</span> -->
                  <el-select
                    size="small"
                    width="100px"
                    @change="modifyEmotion(scope.row)"
                    v-model="scope.row.emotion"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in scope.row.emotionList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            background
            @current-change="handleCurrentChange"
            :current-page="filterData.pageNum"
            :page-size="filterData.pageSize"
            layout="prev, pager, next"
            :total="filterData.total"
          ></el-pagination>
        </div>
      </template>
      <template v-else>
        <div class="fill_content">请输入关键字搜索</div>
      </template>
    </div>
    <!-- 弹出框 -->
    <copy-props :isVisible.sync="isShowProps" ref="copyRef"></copy-props>
    <sent-alert :isShow.sync="isShowAlert" ref="warnRef" @sendWarnMessage="sendWarnMessage"></sent-alert>
    <collect-prop
      :isShow.sync="isShowCollect"
      ref="collectRef"
      @sendMessage="addCollect"
      @addFolder="addFolder"
    ></collect-prop>
  </div>
</template>
<script>
import "../../assets/css/smartSreach.css";
import $Api from "../../utils/api";
import { formatDate } from "../../utils/common";
import copyProps from "../../components/articleTemplate/copyPorps";
import sentAlert from "../../components/articleTemplate/sentAlert";
import collectProp from "../../components/articleTemplate/collectProp";
export default {
  components: {
    copyProps,
    sentAlert,
    collectProp,
  },
  data() {
    return {
      filterData: {
        searchValue: "", //输入框的搜索值
        filterTimeType: "", //非自定义时间时间范围(1-今天 2-24小时 3-3天 4-7天 5-自定义)
        filterStartTime: "", //自定义开始时间
        filterEndTime: "", //自定义结束时间
        filterEmotionType: 1, // 舆论情绪筛选情绪(1-全部 2-正面 3-负面 4-中立)
        filterFromType: [0], // 来源类型(字典表)
        filterSortType: 1, //筛选排序规则(1-发布时间降序 2-热度降序)
        pageNum: 1, //初始页码
        pageSize: 10, //分页数量
        total: 0, //监测结果总数
        resultWords: "", //结果中搜索
      },
      tableData: [],
      statList: [],
      tableLoading: false,
      defineDate: "", //自定义时间数组选择自定义 筛选开始时间 yyyy-MM-dd HH:mm:ss
      multipleSelection: [],
      dateRangeClass: "dn",
      //弹出框组件样式
      isShowProps: false,
      isShowAlert: false,
      isShowCollect: false,
      memberList: [],
      collectList: [],
      showResult: false,
    };
  },
  computed: {
    filterTimeTypeSelect() {
      return this.filterData.filterTimeType;
    },
  },
  watch: {
    filterTimeTypeSelect(val) {
      if (val == 5) {
        this.dateRangeClass = "";
      } else {
        this.dateRangeClass = "dn";
      }
    },
    /**
     * @description: 监听自定义时间的选择
     */
    defineDate() {
      let { defineDate } = this;
      if (defineDate.length > 0) {
        this.$set(
          this.filterData,
          "filterStartTime",
          this.formatDate(defineDate[0])
        );
        this.$set(
          this.filterData,
          "filterEndTime",
          this.formatDate(defineDate[1])
        );
      }
    },
    "filterData.filterFromType"() {
      this.initSearchList(1);
    },
  },
  mounted() {
    this.fetchMember();
    this.fetchDirList();
  },
  methods: {
    //顶部搜索按钮
    searchInfo() {
      this.showResult = true;
      this.initSearchList(1);
    },
    /**
     * @description: 控制弹窗的显示
     * @param {type} 1预警的显隐 2 复制弹窗的显隐
     * @return {Void}
     */
    controller(data, type) {
      switch (type) {
        case 1: {
          let obj1 = this.$refs["warnRef"].warnList;
          this.$refs["warnRef"].warnList = { ...obj1, ...data };
          this.$refs["warnRef"].objList = this.memberList;
          this.isShowAlert = !this.isShowAlert;
          break;
        }
        case 2: {
          let obj1 = this.$refs["copyRef"].copyData;
          this.$refs["copyRef"].copyData = { ...obj1, ...data };
          this.isShowProps = !this.isShowProps;
          break;
        }
        case 3: {
          this.$refs["collectRef"].collectList.push(data);
          this.$refs["collectRef"].objList = this.collectList;
          this.isShowCollect = !this.isShowCollect;
          break;
        }
      }
    },
    /**
     * @description: 设置排序规则
     * @param {Number} type 1-发布时间降序 2-热度降序
     * @return {Void}
     */
    setSortType(type) {
      this.$set(this.filterData, "filterSortType", type);
      this.initSearchList(1);
    },
    /**
     * @description: 指定页面加载数据
     * @param {Number} i当前加载的页号
     * @return {Void}
     */
    initSearchList(i) {
      this.filterData.pageNum = i;
      this.fetchList();
      this.fetchCatInsList();
    },
    /**
     * @description: 获取各个源的统计结果
     * @return {Void}
     */
    fetchCatInsList() {
      let self = this;
      (async () => {
        let data = await $Api.fetchCatInsList(self.filterData);
        if (data.code == 200) {
          self.$set(self, "statList", data.data);
        }
      })();
    },
    /**
     * @description: 搜索列表方法
     * @return {Void}
     */
    fetchList() {
      let self = this;
      let filterData = this.filterData;
      this.tableLoading = true;
      (async () => {
        try {
          let data = await $Api.fetchSearchList(filterData);
          self.tableLoading = false;
          if (data.code == 200) {
            self.$set(self.filterData, "total", data.total);
            data.rows.map((item) => {
              item.emotionList = [
                { value: 0, label: "中立" },
                { value: 1, label: "正面" },
                { value: -1, label: "负面" },
              ];
              return item;
            });
            self.$set(self, "tableData", data.rows);
          }
        } catch {
          self.tableLoading = false;
        }
      })();
    },
    fetchMember() {
      let self = this;
      (async () => {
        let data = await $Api.fetchMember();
        if (data.code == 200) {
          self.$set(self, "memberList", data.data);
        }
      })();
    },
    fetchDirList() {
      let self = this;
      (async () => {
        let data = await $Api.fetchDirList();
        if (data.code == 200) {
          self.$set(self, "collectList", data.data);
          self.$nextTick(() => {
            self.$refs["collectRef"].objList = data.data;
          });
        }
      })();
    },
    /**
     * @description: 发送预警
     * @param {Object} 子组件传过来的预警数据
     * @return {Void}
     */
    sendWarnMessage(data) {
      let self = this;
      (async () => {
        let res = await $Api.sentWarn(data);
        if (res.code == 200) {
          self.isShowAlert = false;
          self.$message.success("预警发送成功");
        }
      })();
    },
    addCollect(data) {
      let self = this;
      (async () => {
        let res = await $Api.addCollect(data);
        if (self.multipleSelection.length) {
          self.$refs.multipleTable.clearSelection();
          self.$refs["collectRef"].collectList = [];
        }
        if (res.code == 200) {
          self.isShowCollect = false;
          self.$message.success("收藏成功");
          self.fetchList();
        }
      })();
    },
    /**
     * @description: 取消收藏
     * @param {type}
     * @return {Void}
     */
    cancelCollect({ collectId: id }) {
      let self = this;
      (async () => {
        let res = await $Api.cancelCollect(id);
        if (res.code == 200) {
          self.$message.success("取消收藏成功");
          self.fetchList();
        }
      })();
    },
    /**
     * @description: 多选择收藏
     * @return {Void}
     */
    addCollection() {
      if (!this.multipleSelection.length) {
        this.$message.warning("请先选择需要收藏的素材");
        return;
      }
      this.$refs["collectRef"].collectList = this.multipleSelection;
      this.$refs["collectRef"].objList = this.collectList;
      this.isShowCollect = !this.isShowCollect;
    },
    addFolder({ folderName }) {
      let self = this;
      (async () => {
        let res = await $Api.addFolder({ folderName });
        if (res.code == 200) {
          self.$refs["collectRef"].folderName = "";
          self.$message.success("添加收藏夹成功");
          self.fetchDirList();
        }
      })();
    },
    /**
     * @description: 修改情绪
     * @param {Object} 当前文章的参数
     * @return {Void}
     */
    modifyEmotion({ rowKey, publishTime, emotion }) {
      let self = this;
      (async () => {
        let res = await $Api.modifyEmotion({ rowKey, publishTime, emotion });
        if (res.code == 200) {
          self.$message.success("修改情绪值成功");
          self.fetchList();
        }
      })();
    },
    /**
     * @description: 添加素材库
     * @return {Void}
     */
    multiAddDir() {
      let self = this;
      if (self.multipleSelection.length == 0) {
        self.$message.warning("请先选择素材");
        return;
      }
      (async () => {
        let res = await $Api.multiAddDir(self.multipleSelection);
        if (res.code == 200) {
          self.$message.success("添加素材成功");
          self.$refs.multipleTable.clearSelection();
        }
      })();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    /**
     * @description: 列表勾选
     * @param {Object} 单个列表项
     * @return {Void}
     */
    handleSelectionChange(val) {
      this.$set(this, "multipleSelection", val);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.initSearchList(val);
    },
    /**
     * @description: 对时间进行格式化
     * @param {String}  time时间字符串
     * @return {String} 格式化后的时间字符串
     */
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss"); //年-月-日 时分
    },
  },
};
</script>